package com.grape.crm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grape.crm.dao.CustomerRepository;
import com.grape.crm.domain.Customer;
import com.grape.crm.service.CustomerService;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
	
	@Autowired
	private CustomerRepository cr;
	
	@Override
	public List<Customer> a() {
		return cr.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> b(String b1) {
		return cr.findByFixedAreaId(b1);
	}

	@Override
	public void c(String c1, String c2) {
		
		// 关联之前清除所有以完成的关联信息以实现取消关联
		cr.clearFixedAreaId(c1);
		
		// System.out.println("远程服务层             >>客户id:"+c2+"       定区id:"+c1);
		
		// 剪开客户id数组,分别关联定区
		String[] split = c2.split(",");
		for (String str : split) {
			// 一切健壮性判断都抵不过一个try	catch
			try {
				Integer CusId = Integer.parseInt(str);
				cr.updateFixedAreaId(c1,CusId);
			} catch (Exception e) {
				System.out.println("奇怪的数据格式>>>>>>>>>>>>"+c2);
				return;
			}
			
		}
		
	}

	@Override
	public void saveOne(Customer customer) {
		cr.save(customer);
	}

	@Override
	public Customer activeMail(String telephone) {
		/*原生自带BUG:一个手机号能重复注册,这导致激活邮件激活的总是这个手机号的第一个账号
		解决:将手机号置为主键,在异步操作保存用户时返回这个错误,不让他注册*/
		
		List<Customer> lc = cr.findByTelephoneIs(telephone);
		Customer cus = lc.get(0);
		if (cus.getType() == null) {
			cus.setType(1);
			
			return cus;
		}else {
			
			return new Customer();
		}
	}

	@Override
	public String login(String telephone, String password) {
		Customer cus = cr.findByTelephoneAndPassword(telephone,password);
		if (cus == null) {
			return null;
		}
		
		return cus.getId().toString();
	}

	@Override
	public String findDqidByAddress(String address) {
		Customer customer = cr.findByAddress(address);
		if (customer!=null) {
			return customer.getFixedAreaId();
		}
		
		return "null";
	}

}
